import * as vscode from "vscode";
interface VariableValueMap {
  [key: string]: string[];
}
export class CssReplace {
  getCssProperties(text: string): { property: string; value: string }[] {
    const regex = /([a-zA-Z-]+)\s*:\s*([^;]+?)\s*;/g;
    let match;
    const cssProperties: { property: string; value: string }[] = [];
    while ((match = regex.exec(text)) !== null) {
      const property = match[1].trim();
      const value = match[2].trim();
      cssProperties.push({ property, value });
    }
    return cssProperties;
  }

  // css变量替换
  async replaceCssVariables(
    cssArray: VariableValueMap,
    content: string
  ): Promise<string | undefined> {
    if (!cssArray || !content) return;
    const cssProperties = this.getCssProperties(content);
    const config = vscode.workspace.getConfiguration("cssVariableAutocomplete");
    const skipProperties: string[] = config.get("skipProperties", []);
    cssProperties.forEach(({ property, value }) => {
      if (skipProperties.includes(property)) {
        return;
      }
      let resolvedValue: string | undefined = cssArray[value]?.[0];
      if (resolvedValue !== undefined && value) {
        resolvedValue = `var(${resolvedValue})`;
        const regex = new RegExp(`(${property}\\s*:\\s*)${value}(\\s*;)`, "g");
        content = content.replace(regex, `$1${resolvedValue}$2`);
      }
    });
    return content;
  }
}
